<template>
  <el-form label-position="top">
    <el-form-item label="七、经费预算明细表 （单位：万元））" />
  </el-form>
  <div v-for="(item, index) in options" :key="index">
    <vxe-form>
      <vxe-form-item>
        <template #default>
          <el-select
            v-model="item.budgetSaveReqVO.fundSource"
            placeholder="请选择"
            style="width: 200px"
          >
            <el-option
              v-for="sub in dictStore.getDictType('jfys_type')"
              :key="sub.value"
              :label="sub.label"
              :value="sub.value"
            />
          </el-select>
        </template>
      </vxe-form-item>
      <vxe-form-item>
        <template #default>
          <el-date-picker
            v-model="item.budgetSaveReqVO.year"
            type="year"
            format="YYYY"
            value-format="YYYY"
            placeholder="请选择年份"
            style="width: 200px"
          />
        </template>
      </vxe-form-item>
      <vxe-form-item>
        <template #default>
          <el-select
            v-model="item.budgetSaveReqVO.departmentId"
            placeholder="请选择部门"
            style="width: 200px"
          >
            <el-option
              v-for="sub in depts"
              :key="sub.id"
              :label="sub.name"
              :value="sub.id"
            />
          </el-select>
        </template>
      </vxe-form-item>
      <vxe-form-item>
        <template #default>
          <el-cascader
            :ref="(el) => (FormRef[index] = el)"
            v-model="item.budgetSaveReqVO.fundTypeId"
            :options="budTypes"
            :props="optionProps"
            placeholder="请选择"
            style="width: 200px"
            @change="handleChange($event, index)"
          />
        </template>
      </vxe-form-item>
    </vxe-form>
    <vxe-table
      v-if="item.budgetSaveReqVO.fundTypeId"
      border
      show-overflow
      :data="item.detailSaveReqVOS"
      :column-config="{ resizable: true }"
      :edit-config="{ trigger: 'click', mode: 'row' }"
    >
      <vxe-column type="seq" width="60" />
      <template v-for="sub in item.budgetSaveReqVO.fieldJson" :key="sub">
        <vxe-column
          :field="sub"
          :title="sub"
          :edit-render="{ autofocus: '.vxe-input--inner' }"
        >
          <template #edit="{ row }">
            <vxe-input v-model="row[sub]" type="text" />
          </template>
        </vxe-column>
      </template>
      <vxe-column title="操作" width="80">
        <template #default="{ rowIndex }">
          <vxe-button
            mode="text"
            status="primary"
            @click="removeTable(index, rowIndex)"
          >
            移除
          </vxe-button>
        </template>
      </vxe-column>
    </vxe-table>
    <el-button
      v-if="item.budgetSaveReqVO.fundTypeId"
      style="margin-top: 20px"
      type="primary"
      :icon="Plus"
      @click="handleAddTable(index)"
    >
      增加预算条目
    </el-button>
  </div>
  <el-button
    style="margin-top: 20px"
    type="primary"
    :icon="Plus"
    @click="handleAdd"
  >
    增加预算表
  </el-button>
</template>

<script setup>
  import { Plus } from '@element-plus/icons-vue'
  import { useDictStore } from '@/store/modules/dict'
  import { getDeptPage } from '@/api/system/dept/index'
  import { budgetTypeTree } from '@/api/project/index'

  const dictStore = useDictStore()
  const $baseMessage = inject('$baseMessage')

  const FormRef = ref([])

  const depts = ref([])
  const budTypes = ref([])
  const optionProps = {
    value: 'id',
    label: 'name',
    children: 'childList',
    emitPath: false, //只传最后一级id
  }

  const options = ref([
    {
      budgetSaveReqVO: {
        fundSource: '',
        year: '',
        departmentId: '',
        fundTypeId: '',
        fieldJson: [],
      },
      detailSaveReqVOS: [],
    },
  ])

  const getDepts = () => {
    getDeptPage().then((res) => {
      if (res.code == 0 || res.code == 200) {
        depts.value = res.data || []
      }
    })
  }

  const getBudgetTree = () => {
    budgetTypeTree().then((res) => {
      if (res.code == 0 || res.code == 200) {
        budTypes.value = res.data || []
      }
    })
  }

  const handleChange = (value, index) => {
    const fieldJson = JSON.parse(
      FormRef.value[index].getCheckedNodes()[0].data.fieldJson.value
    )
    options.value[index].budgetSaveReqVO.fieldJson = fieldJson
  }

  const handleAdd = () => {
    options.value.push({
      budgetSaveReqVO: {
        fundSource: '',
        year: '',
        departmentId: '',
        fundTypeId: '',
      },
      detailSaveReqVOS: [],
    })
  }

  const handleAddTable = (index) => {
    const fieldJson = options.value[index].budgetSaveReqVO.fieldJson
    const filedMap = {}
    fieldJson.forEach((item) => {
      filedMap[item] = ''
    })
    options.value[index].detailSaveReqVOS.push(filedMap)
  }

  const removeTable = (index, rowIndex) => {
    options.value[index].detailSaveReqVOS.splice(rowIndex, 1)
  }

  const getFormData = () => {
    if (!options.value.length) {
      $baseMessage('请填写完整的经费预算明细表', 'error')
      return false
    }
    for (let i = 0; i < options.value.length; i++) {
      if (!options.value[i].detailSaveReqVOS.length) {
        $baseMessage('请填写完整的经费预算明细表', 'error')
        return false
      }
      for (const key in options.value[i].budgetSaveReqVO) {
        if (
          !options.value[i].budgetSaveReqVO[key] &&
          !['departmentName', 'fundTypeName'].includes(key)
        ) {
          $baseMessage('请填写完整的经费预算明细表', 'error')
          return false
        }
      }

      for (
        let subIndex = 0;
        subIndex < options.value[i].detailSaveReqVOS.length;
        subIndex++
      ) {
        for (const key in options.value[i].detailSaveReqVOS[subIndex]) {
          if (!options.value[i].detailSaveReqVOS[subIndex][key]) {
            $baseMessage('请填写完整的经费预算明细表', 'error')
            return false
          }
        }
      }
    }

    const params = options.value.map((item) => {
      return {
        ...item,
        detailSaveReqVOS: item.detailSaveReqVOS.map((key) => {
          return {
            cost: JSON.stringify(key),
          }
        }),
      }
    })
    return { budgetAndDetailVO: params }
  }

  getDepts()
  getBudgetTree()

  const setFormData = async ({ budgetAndDetailVO }) => {
    options.value = []
    await nextTick()
    options.value = budgetAndDetailVO.map((item) => {
      return {
        budgetSaveReqVO: {
          ...item.budgetSaveReqVO,
          fundTypeId: Number(item.budgetSaveReqVO.fundTypeId),
        },
        detailSaveReqVOS: item.detailSaveReqVOS.map((sub) => {
          const cost = JSON.parse(sub.cost)
          return {
            ...sub,
            ...cost,
          }
        }),
      }
    })
    console.log(options.value)
  }

  defineExpose({ getFormData, setFormData })
</script>

<style lang="scss" scoped></style>
